import { getMe } from '@/api/user'
import { getToken, setToken, clearToken } from '@/utils/userManage'
import { User } from '@/modules/user'
import { $warn, $loading, $hideLoading, $pushTo } from '@/utils/functions'
import { initNickname } from '@/constants/index'

interface UserType {
  isInit: boolean, // 是否初始化完成
  isLogin: boolean, // 是否已经登录
  userInfo: User | null // 用户信息
}
interface loginSuccessType {
  userInfo:User,
  token:string
}

export default {
  state: ():UserType => {
    return {
      isInit: false,
      isLogin: false,
      userInfo: null
    }
  },
  getters: {
    /**
     * 获取用户信息
     */
    getUserInfo(state:UserType) {
      if (!state.userInfo) {
        return null
      }
      /* 初始化一些值 */
      state.userInfo.userInfo.nickname = state.userInfo.userInfo.nickname || initNickname
      return JSON.parse(JSON.stringify(state.userInfo))
    }
  },
  mutations: {
    finishInit(state:UserType) {
      state.isInit = true
    },
    /**
     * 设置用户信息
     * @param {Object} userInfo
     */
    setUserInfo(state:UserType, userInfo:User) {
      /* 一些默认值 */
      state.userInfo = {
        ...state.userInfo,
        ...userInfo
      }
    },
    /**
     * 登录成功，验证码登录或者自动登录
     * @param {Object} userInfo 用户信息
     * @param {String} token 用户凭证
     */
    loginSuccess(state:UserType, { userInfo, token }:loginSuccessType) {
      /* 如果没有token，则不要刷新 */
      token && setToken(token)
      state.userInfo = userInfo
      state.isLogin = true
    },
    /**
     * 退出登录
     */
    loginOut(state:UserType, msg = '') {
      $pushTo('Home')
      state.userInfo = null
      state.isLogin = false
      $warn(msg)
      clearToken()
    },
  },
  actions: {
    /**
     * 自动登录，如果有token则获取个人信息，末尾触发初始化结束方法
     */
    async autoLogin({ commit }:{commit:any}) {
      const token = getToken()

      if (token) {
        try {
          $loading()
          const res = await getMe()

          commit('loginSuccess', {
            userInfo: res.data,
          })
          console.log('自动登录')

        } catch (err) {
          console.log(err)
        }
        $hideLoading()
      }
      commit('finishInit')
    }
  }
}
